﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace CoolCode.Dynamic
{
    public static class InvokeMemberExtensions
    {
        public static void SetValue<T>(this object obj, string propertyName, object propertyValue)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(T), "x");
            ParameterExpression value = Expression.Parameter(typeof(string), "propertyValue");
            MethodInfo setter = typeof(T).GetMethod("set_" + propertyName);
            MethodCallExpression call = Expression.Call(parameter, setter, value);
            LambdaExpression lambda = Expression.Lambda(call, parameter, value);
            var exp = lambda.Compile();
            exp.DynamicInvoke(obj, propertyValue);
        }
    }
}
